import React, { Component } from 'react';
import { Row, Col, Button } from 'antd';
import _ from 'underscore';
import './home.less';

export default class Home extends Component {
    handleClick = () => {
        console.log('do click');
    }

    debounce = (fn, delay) => {
        return function () {
            console.log('do debounce');
            // 清除未执行的定时器
            // 每间隔delay时间去准备执行一个fn函数，它不一定能执行（可能在执行前被删除）
            const that = this;
            const args = arguments;
            if (fn.timeoutId) {
                clearTimeout(fn.timeoutId);
            }
            fn.timeoutId = setTimeout(function () {

                fn.apply(that, args);
                delete fn.timeoutId;
            }, delay)
        }
    }

    throttle = (fn, delay) => {
        // 忽略多余的click事件
        let start = 0;
        return function () {
            const nowT = Date.now();
            console.log('do throttle', nowT - start);
            if (nowT - start > delay) {
                // console.log(start, nowT)
                fn.apply(this, arguments);
                start = nowT;
            }
        }
    }

    render() {
        return (
            <div className="container">
                <Row style={{padding: 20}}>
                    <Col span={8}>
                        <div>自定义实现防抖与截流函数</div>
                    </Col>
                    <Col span={8}>
                        <Button
                            type="primary"
                            onClick={this.debounce(this.handleClick, 1000)}
                        >
                            Debounce 防抖
                            </Button>
                    </Col>
                    <Col span={8}>
                        <Button
                            type="default"
                            onClick={this.throttle(this.handleClick, 2000)}
                        >
                            Throttle 截流
                            </Button>
                    </Col>
                </Row>
                <Row style={{padding: 20}}>
                    <Col span={8}>
                        <div>Underscro防抖与截流</div>
                    </Col>
                    <Col span={8}>
                        <Button
                            type="primary"
                            onClick={_.debounce(this.handleClick, 1000)}
                        >
                            Debounce 防抖
                            </Button>
                    </Col>
                    <Col span={8}>
                        <Button
                            type="default"
                            onClick={_.throttle(this.handleClick, 2000)}
                        >
                            Throttle 截流
                            </Button>
                    </Col>
                </Row>
            </div>
        )
    }
}
